const Router = require('koa-router')()
const mongoose = require('mongoose')

Router.post('/addAddress', async (ctx) => {
  // ctx.body = {
  //   code: 200,
  //   data: ctx.request.body
  // }
  const address = ctx.request.body
  const phone = ctx.session.phone
  console.log(phone, address)
  try {
    const table = mongoose.model('bee')
    await table.findOneAndUpdate({ phone }, { $push: { address: address } }, { useFindAndModify: false })
    ctx.body = {
      code: 200,
      msg: '成功'
    }
  } catch (err) {
    console.log(err)
    ctx.body = {
      code: 400,
      msg: '未知错误'
    }
  }
})
Router.post('/setdefault', async (ctx) => {
  const table = mongoose.model('bee')
  const phone = ctx.session.phone
  const iid = ctx.request.body.iid
  try {
    await table.updateMany({ phone }, { $set: { 'address.$[].checked': false } })
    await table.updateOne({ phone, 'address.iid': iid }, { $set: { 'address.$.checked': true } })
    ctx.body = {
      code: 200,
      msg: '成功了'
    }
  } catch (err) {
    ctx.body = {
      code: 300,
      msg: '失败了'
    }
  }
})
Router.post('/deleteAddress', async (ctx) => {
  const table = mongoose.model('bee')
  const iid = ctx.request.body.iid
  const phone = ctx.session.phone
  console.log('dele')
  try {
    await table.updateOne({ phone }, { $pull: { address: { iid: iid } } }, { useFindAndModify: false, multi: true })

    ctx.body = {
      code: 200,
      msg: '成功了'
    }
  } catch (err) {
    ctx.body = {
      code: 300,
      msg: '失败了'
    }
  }
})
Router.post('/editAddress', async (ctx) => {
  const table = mongoose.model('bee')
  const iid = ctx.request.body.iid
  const phone = ctx.session.phone
  console.log(ctx.request.body)
  try {
    // await table.updateOne({ phone }, { $pull: { address: { iid: iid } } }, { useFindAndModify: false, multi: true })
    await table.updateOne({ phone, 'address.iid': iid }, { $set: { 'address.$': ctx.request.body } })
    console.log('11111')
    ctx.body = {
      code: 200,
      msg: '成功了'
    }
  } catch (err) {
    ctx.body = {
      code: 300,
      msg: '失败了'
    }
  }
})
module.exports = Router
